package com.itheima.app.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.app.mq.MovementMQSend;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.vo.CommentVo;
import com.itheima.domain.vo.MovementVo;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.MovementService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.baomidou.mybatisplus.core.toolkit.IdWorker.getId;

@Component //加入spring容器
public class MovementManager {

    @Reference //dubbo
            MovementService movementService;

    @Autowired
    OssTemplate ossTemplate;

    @Reference
    UserInfoService userInfoService;

    @Reference
    CommentService commentService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RocketMQTemplate rocketMQTemplate;

    @Autowired
    MovementMQSend movementMQSend;


    public ResponseEntity save(Movement movement, MultipartFile[] imageContent) throws IOException {
        //0.创建存放图片路径的集合
        List<String> medias = new ArrayList<>();

        //1.将图片保存到oss上,返回图片地址集合
        if (ArrayUtil.isNotEmpty(imageContent)) {
            for (MultipartFile file : imageContent) {
                //上传到oss上,返回地址
                String url = ossTemplate.upload(file.getOriginalFilename(), file.getInputStream());

                //将路径保存到集合中
                medias.add(url);
            }
        }

        //2.封装动态信息(图片集合,用户id..)
        //2.1 先手动设置id
        movement.setId(ObjectId.get());

        movement.setUserId(UserHolder.get().getId());//用户id
        movement.setMedias(medias);//图片路径
        movement.setSeeType(1);//此版本不涉及,写死了
        //TODO 等学完华为内容审核之后,再修改,暂时写死
        movement.setState(0);//审核状态
        movement.setCreated(System.currentTimeMillis());

        //3.调用service完成保存操作
        movementService.save(movement);

        //4.将movement对象放入mq中
        rocketMQTemplate.convertAndSend("tanhua-movement",movement);

        //将用户的操作行为放入mq中
        movementMQSend.movementMQSend(UserHolder.get().getId(),movement.getId().toString(),movementMQSend.MOVEMENT_PUBLISH);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity findMyMovementByPage(int pageNum, int pageSize, Long userId) {
        //1.获取用户id
        //2.查询用户的信息
        UserInfo userInfo = userInfoService.findById(userId);

        //3.调用mongoservice查询当前页数据
        PageBeanVo page = movementService.findMyMovementByPage(pageNum, pageSize, userId);

        //4.遍历当前页的数据集合,获取每个动态,封装成动态vo对象(动态+userInfo)
        //4.1 获取当前页的动态集合
        List<Movement> items = (List<Movement>) page.getItems();

        //4.2 创建一个MovementVo集合
        List<MovementVo> movementVoList = new ArrayList<>();

        if (CollUtil.isNotEmpty(items)) {
            for (Movement movement : items) {
                //4.3 封装vo对象
                MovementVo movementVo = new MovementVo();

                //先封装用户信息
                movementVo.setUserInfo(userInfo);
                //再封装动态信息
                movementVo.setMovement(movement);

                //判断当前用户有无点赞
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LIKE,userId,movement.getId()))) {
                    movementVo.setHasLiked(1);
                }

                //4.4 放入list中
                movementVoList.add(movementVo);
            }
        }


        //5.将volist设置到pageBeanVo,然后返回
        page.setItems(movementVoList);
        return ResponseEntity.ok(page);
    }


    public ResponseEntity findFriendMovementByPage(int pageNum, int pageSize) {
        //1.获取用户id
        Long userId = UserHolder.get().getId();

        //2.调用mongoservice查询当前页数据
        PageBeanVo page = movementService.findFriendMovementByPage(pageNum, pageSize, userId);

        //3.遍历当前页的数据集合,获取每个动态,封装成动态vo对象(动态+userInfo)
        //3.1 创建一个MovementVoList
        List<MovementVo> movementVoList = new ArrayList<>();

        //3.2 获取动态集合,遍历集合
        List<Movement> items = (List<Movement>) page.getItems();
        if (CollUtil.isNotEmpty(items)) {
            for (Movement movement : items) {
                //3.3 获取每个动态的发布人id
                Long friendId = movement.getUserId();

                //3.4 通过发布人id,查询改用户的userInfo
                UserInfo userInfo = userInfoService.findById(friendId);

                //3.5 封装movementVo对象
                MovementVo movementVo = new MovementVo();

                //先封装用户信息,在封装movement
                movementVo.setUserInfo(userInfo);
                movementVo.setMovement(movement);

                //判断当前用户有无点赞
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LIKE,userId,movement.getId()))) {
                    movementVo.setHasLiked(1);
                }

                //3.6 将movementVo对象放入list中
                movementVoList.add(movementVo);
            }
        }

        //4.将volist设置到pageBeanVo,然后返回
        page.setItems(movementVoList);

        return ResponseEntity.ok(page);
    }

    public ResponseEntity findRecommendMovementByPage(int pageNum, int pageSize) {
        //1.获取当前用户的id
        Long userId = UserHolder.get().getId();

        //2.调用mongoservice查询当前页数据
        PageBeanVo page = movementService.findRecommendMovementByPage(pageNum, pageSize, userId);

        //3.遍历动态集合,获取每个动态信息,通过动态信息查询所属用户信息,封装movementVo对象,放入一个集合中
        //3.1 创建movementVoList
        List<MovementVo> movementVoList = new ArrayList<>();

        //3.2 获取动态集合,遍历它
        List<Movement> items = (List<Movement>) page.getItems();
        if (CollUtil.isNotEmpty(items)) {
            for (Movement movement : items) {
                //3.3 获取每个动态,及其动态所属用户id
                //3.4 通过用户id 查询用户信息
                UserInfo userInfo = userInfoService.findById(movement.getUserId());

                //3.5 封装vo对象
                MovementVo movementVo = new MovementVo();

                //先封装用户信息,再封装动态信息
                movementVo.setUserInfo(userInfo);
                movementVo.setMovement(movement);

                //判断当前用户有无点赞
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LIKE,userId,movement.getId()))) {
                    movementVo.setHasLiked(1);
                }

                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LOVE,userId,movement.getId()))) {
                    movementVo.setHasLoved(1);
                }

                //3.6 将vo放入list中
                movementVoList.add(movementVo);
            }
        }

        //4.将voList设置给pageBeanVo
        page.setItems(movementVoList);

        //5.返回pageBeanVo
        return ResponseEntity.ok(page);
    }

    //点赞
    public ResponseEntity saveMovementLike(String movementId) {
        //0.获取当前用户id
        Long userId = UserHolder.get().getId();
        //1.创建comment,封装
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());//创建时间
        comment.setPublishId(new ObjectId(movementId));//动态id
        comment.setCommentType(1);//类型:点赞
        comment.setUserId(userId);//用户id

        //2.调用commentService完成保存,返回最新的点赞数
        int count = commentService.save(comment);

        //3.保存点赞的标识(redis)
        //stringRedisTemplate.opsForValue().set("movement_like:用户id_动态id",1);
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.MOVEMENT_LIKE,userId,movementId),"1");

        //将用户的操作行为放入mq中
        movementMQSend.movementMQSend(UserHolder.get().getId(),movementId,movementMQSend.MOVEMENT_LIKE);

        //3.返回点赞数
        return ResponseEntity.ok(count);
    }

    //取消点赞
    public ResponseEntity deleteMovementLike(String movementId) {
        //1.获取用户id
        Long userId = UserHolder.get().getId();

        //2.确定操作的类型1
        //3.调用service完成删除操作,返回最新的点赞数
        int count = commentService.delete(userId, 1, movementId);

        //4.删除redis中的标识
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.MOVEMENT_LIKE,userId,movementId));

        //将用户的操作行为放入mq中
        movementMQSend.movementMQSend(UserHolder.get().getId(),movementId,movementMQSend.MOVEMENT_DISLIKE);


        //5.返回点赞数
        return ResponseEntity.ok(count);
    }

    //喜欢
    public ResponseEntity saveMovementLove(String movementId) {
        //0.获取用户id
        Long userId = UserHolder.get().getId();

        //1.创建comment,封装
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());//创建时间
        comment.setPublishId(new ObjectId(movementId));//动态id
        comment.setCommentType(3);//类型:点赞
        comment.setUserId(userId);//用户id

        //2.调用commentService完成保存,返回最新的喜欢数
        int count = commentService.save(comment);

        //3.保存喜欢的标识(redis)
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.MOVEMENT_LOVE,userId,movementId),"1");

        //将用户的操作行为放入mq中
        movementMQSend.movementMQSend(UserHolder.get().getId(),movementId,movementMQSend.MOVEMENT_LOVE);


        //4.返回喜欢数
        return ResponseEntity.ok(count);
    }

    //取消喜欢
    public ResponseEntity deleteMovementLove(String movementId) {
        //1.获取用户id
        Long userId = UserHolder.get().getId();

        //2.确定操作的类型
        //3.调用service完成删除操作,返回最新的喜欢数
        int count = commentService.delete(userId, 3, movementId);

        //4.删除redis中的标识
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.MOVEMENT_LOVE,userId,movementId));

        //将用户的操作行为放入mq中
        movementMQSend.movementMQSend(UserHolder.get().getId(),movementId,movementMQSend.MOVEMENT_DISLOVE);


        //5.返回喜欢数
        return ResponseEntity.ok(count);
    }

    public ResponseEntity findById(String movementId) {
        //1.调用动态service查询某个动态
        Movement movement = movementService.findById(movementId);

        //2.在动态中获取用户id,调用UserInfoService查询用户信息
        UserInfo userInfo = userInfoService.findById(movement.getUserId());

        //3.创建MovementVo对象,封装
        MovementVo movementVo = new MovementVo();

        //先用户,再动态
        movementVo.setUserInfo(userInfo);
        movementVo.setMovement(movement);

        //将用户的操作行为放入mq中
        movementMQSend.movementMQSend(UserHolder.get().getId(),movementId,movementMQSend.MOVEMENT_BROWSE);


        //4.返回vo
        return ResponseEntity.ok(movementVo);
    }

    public ResponseEntity findMovementCommentByPage(int pageNum, int pageSize, String movementId) {
        //1.调用commentService查询当前页的数据
        PageBeanVo page = commentService.findMovementCommentByPage(pageNum, pageSize, movementId);

        //2.获取当前页中评论集合,遍历它
        List<Comment> items = (List<Comment>) page.getItems();

        //2.1 创建一个voList
        List<CommentVo> commentVoList = new ArrayList<>();
        Long id=UserHolder.get().getId();

        //2.2 遍历
        if (CollUtil.isNotEmpty(items)) {
            for (Comment comment : items) {
                //3.获取每个评论的用户id
                Long userId = comment.getUserId();

                //4.通过用户id查询用户的userInfo
                UserInfo userInfo = userInfoService.findById(userId);

                //5.封装CommentVo(评论+用户),放入voList中
                CommentVo commentVo = new CommentVo();

                commentVo.setAvatar(userInfo.getAvatar());
                commentVo.setNickname(userInfo.getNickname());

                commentVo.setId(comment.getId().toString());
                commentVo.setContent(comment.getContent());
                commentVo.setCreateDate(DateUtil.format(new Date(comment.getCreated()),"yyyy-MM-dd HH:mm:ss"));

                if(stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.COMMENT_LIKE,id,comment.getId()))){
                    commentVo.setHasLiked(1);
                }

                commentVoList.add(commentVo);

            }
        }

        //6.将voList设置分页对象
        page.setItems(commentVoList);

        //7.返回分页对象
        return ResponseEntity.ok(page);
    }



    public ResponseEntity saveMovementComment(String movementId, String content) {
        //1.获取当前用户
        Long userId = UserHolder.get().getId();

        //2.创建Comment,封装comment
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setPublishId(new ObjectId(movementId));//动态id
        comment.setCommentType(2);//类型为评论
        comment.setUserId(userId);//评论人id
        comment.setContent(content);//内容


        //3.调用service完成保存操作
        int count = commentService.save(comment);


        //将用户的操作行为放入mq中
        movementMQSend.movementMQSend(UserHolder.get().getId(),movementId,movementMQSend.MOVEMENT_COMMENT);


        return ResponseEntity.ok(null);
        //按理来说应该返回最新的评论列表
        //return findMovementCommentByPage(1,8,movementId);
    }
    //评论点赞
    public ResponseEntity saveCommentLike(String commentId) {
        //获取用户id
        Long userId = UserHolder.get().getId();

        /*//1.创建comment,封装
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());//创建时间
        comment.setPublishId(new ObjectId(commentId));//动态id
        comment.setCommentType(6);//类型:点赞
        comment.setUserId(userId);//用户id
        //调用commentService完成保存,返回最新的喜欢数*/
        int count = commentService.saveCommentLike(commentId,6);

        //保存喜欢的标识(redis)
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.COMMENT_LIKE,userId,commentId),"1");

        //返回喜欢数
        return ResponseEntity.ok(count);

    }
    //取消评论点赞
    public ResponseEntity deleteCommentLike(String commentId) {
        //获取用户id
        Long userId = UserHolder.get().getId();

        //调用service完成删除操作,返回最新的喜欢数
        int count = commentService.deleteCommentLike(userId,6,commentId);

        //删除redis中的标识
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.COMMENT_LIKE,userId,commentId));

        //返回喜欢数
        return ResponseEntity.ok(count);

    }
}

